package com.cdyZuul.ZuulFilter;

/**
 * @author ：cdy
 * @date ：Created in 2020/11/12 9:58
 * @description：www.cdyong.cn
 */
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import entity.Result;
import entity.StatusCode;
import entity.authToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登录过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {

    //排除过滤的 uri 地址
    private static final String LOGIN_URI = "/user/login";
    private static final String REGISTER_URI = "/user/register";
    private static final String AUTH_TOKEN = "Authorization";

    @Autowired(required = false)
     private authToken authToken;

    /**
     * 过滤器类型，前置过滤器
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器顺序，越小越先执行
     */
    @Override
    public int filterOrder() {
        return 4;
    }

    /**
     * 过滤器是否生效
     * 返回true代表需要权限校验，false代表不需要用户校验即可访问
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String requestURI = request.getRequestURI();
        //放行路由
        if(LOGIN_URI.equals(requestURI)||REGISTER_URI.equals(requestURI)){

            return false;
        }
        return true;
    }

    /**
     * 业务逻辑
     * 只有上面返回true的时候，才会进入到该方法
     */
    @Override
    public Object run() throws ZuulException {
        if(authToken==null)return  null;

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();

        String token = request.getHeader(AUTH_TOKEN);
         if(!authToken.checker(token)){
             //不存在，直接返回验证失败，让其重新登录
             response.setContentType("application/json; charset=utf8");
             requestContext.setSendZuulResponse(false);//不会被zuul路由转发，也就是不会请求到后端具体的服务。但是如果当前filter后面还有其他filter的话，其他filter依然会执行
             response.setStatus(401);
             requestContext.setResponseBody(new Result(false, StatusCode.ACCESSERROR,"权限不足").toString());
         }
         else
             requestContext.addZuulRequestHeader(AUTH_TOKEN, token);  //设置请求头转发到微服务

        return null;
    }
}
